<template>
  <base-page-view class-name="page-container product-material-detail">
    <!-- tab -->
    <view v-if="show_type===1" class="sticky-wrap">
      <view class="tab-list">
        <view v-for="(item, index) in tabList" :key="index" class="tab-item" :class="{active: currentTab === item.type}" @click="tabClick(item)">{{ item.title }}</view>
      </view>
    </view>

    <!-- 商品素材 -->
    <template v-if="pageloaded && show_type===1">
      <!-- 商品介绍 -->
      <view v-if="currentTab === 'GOODS_INFO'" class="goods-desc">
        <view v-for="(item, index) in goodsDescImgs" :key="index" :style="'width:100%; height:'+item.imgHeight+'rpx'">
          <b-image v-if="item.resourceType===1" class-name="img" :src="item.resourceUrl" mode="aspectFill" />
        </view>
        <template v-if="!goodsDescImgs.length">
          <msg-page type="empty_list" text="暂无数据" />
        </template>
      </view>
      <!-- 海报/视频 -->
      <view v-else-if="currentTab === 'POSTER_VIDEO'" class="poster-video">
        <view class="video-list">
          <view v-for="(item,index) in videos" :key="index" class="video-item">
            <video :ref="'video'+index" :data-id="index" :src="item.resourceUrl" :poster="item.videoPreviewImg" :custom-cache="false" :controls="true" @play="videoPlay"></video>
            <!-- #ifndef H5 -->
            <b-image class-name="download" src="/static/images/material/btn_download.png" mode="aspectFit" :is-asset="true" @click="download([item], 'Video')" />
            <!-- #endif -->
          </view>
        </view>
        <view class="pic-water-fall">
          <waterFall ref="waterFall" :list="posterImgs" :min-height="waterFallMinHeight" :delay="0">
            <template v-slot="{ item, columnIndex, index, list }">
              <view class="pic-item" :class="{mini: columnIndex === 1 && index===0 }" :style="'height:'+item.imgContainerHeight+'rpx'" @click="itemClick(item, list)">
                <b-image v-if="item.resourceType===1" class="pic" :src="item.resourceUrl" :style="'height:'+item.imgHeight+'rpx'" mode="aspectFill" />
              </view>
            </template>
            <template v-if="!videos.length && !posterImgs.length" slot="footer">
              <msg-page type="empty_list" text="暂无数据" />
            </template>
          </waterFall>
        </view>
      </view>
      <!-- 产品实验 -->
      <view v-else-if="currentTab === 'PRODUCT_TEST'" class="pic-water-fall">
        <waterFall ref="waterFall" :list="productTests" :min-height="waterFallMinHeight" :delay="0">
          <template v-slot="{ item, columnIndex, index, list }">
            <view class="pic-item" :class="{mini: columnIndex === 1 && index===0 }" :style="'height:'+item.imgContainerHeight+'rpx'" @click="itemClick(item, list)">
              <b-image v-if="item.resourceType===1" class="pic" :src="item.resourceUrl" :style="'height:'+item.imgHeight+'rpx'" mode="aspectFill" />
            </view>
          </template>
          <template v-if="!productTests.length" slot="footer">
            <msg-page type="empty_list" text="暂无数据" />
          </template>
        </waterFall>
      </view>
      <!-- 质检报告 -->
      <view v-else-if="currentTab === 'REPORT'" class="pic-water-fall">
        <waterFall ref="waterFall" :list="reports" :min-height="waterFallMinHeight" :delay="0">
          <template v-slot="{ item, columnIndex, index, list }">
            <view class="pic-item" :class="{mini: columnIndex === 1 && index===0 }" :style="'height:'+item.imgContainerHeight+'rpx'" @click="itemClick(item, list)">
              <b-image v-if="item.resourceType===1" class="pic" :src="item.resourceUrl" :style="'height:'+item.imgHeight+'rpx'" mode="aspectFill" />
            </view>
          </template>
          <template v-if="!reports.length" slot="footer">
            <msg-page type="empty_list" text="暂无数据" />
          </template>
        </waterFall>
      </view>

      <!-- 底部商品 -->
      <footer-bar>
        <view class="goods-block">
          <view class="sub-item" @click="toGoodsDetail">
            <b-image class-name="goods-img" :src="goods.goods_image_url" mode="aspectFill" />
            <view class="right-part">
              <view class="goods-name">{{ goods.goods_name }}</view>
              <view>
                <text class="price">{{ goods.price | formatMoney }}</text>
                <text class="price market-price">{{ goods.market_price | formatMoney }}</text>
              </view>
            </view>
          </view>
          <!-- #ifndef H5 -->
          <b-image class-name="divide" src="/static/images/material/icon_divide.png" mode="aspectFit" :is-asset="true" />
          <view class="btn btn-download" @click="download()">
            <b-image class-name="icon" src="/static/images/material/icon_download.png" mode="aspectFit" :is-asset="true" />
            <view>下载</view>
          </view>
          <view class="btn" @click="showSharePop">
            <b-image class-name="icon" src="/static/images/material/icon_share.png" mode="aspectFit" :is-asset="true" />
            <view>分享</view>
          </view>
          <!-- #endif -->
        </view>
      </footer-bar>
    </template>
    <template v-else-if="pageloaded && show_type===2">
      <!-- 图片 -->
      <view class="pic-water-fall">
        <waterFall ref="waterFall" :list="goodsDescImgs" :min-height="waterFallMinHeight" :delay="0">
          <template v-slot="{ item, columnIndex, index, list }">
            <view class="pic-item" :class="{mini: columnIndex === 1 && index===0 }" :style="'height:'+item.imgContainerHeight+'rpx'" @click="itemClick(item, list)">
              <b-image v-if="item.resourceType===1" class="pic" :x-width="375" :src="item.resourceUrl" :style="'height:'+item.imgHeight+'rpx'" mode="aspectFill" />
            </view>
          </template>
          <template v-if="!goodsDescImgs.length" slot="footer">
            <msg-page type="empty_list" text="暂无数据" />
          </template>
        </waterFall>
      </view>

      <!-- #ifndef H5 -->
      <!-- 底部按钮 -->
      <footer-bar v-if="goodsDescImgs.length">
        <view class="btns-block">
          <view class="btn btn-download" @click="download()">
            <b-image class-name="icon" src="/static/images/material/icon_download.png" mode="aspectFit" :is-asset="true" />
            <view>下载</view>
          </view>
          <b-image class-name="divide" src="/static/images/material/icon_divide.png" mode="aspectFit" :is-asset="true" />
          <view class="btn" @click="showSharePop">
            <b-image class-name="icon" src="/static/images/material/icon_share.png" mode="aspectFit" :is-asset="true" />
            <view>分享</view>
          </view>
        </view>
      </footer-bar>
      <!-- #endif -->
    </template>
    <share ref="sharePop" :share-option="shareOption" :share-types="[3,5]" @btnClick="shareBtnClick" />
  </base-page-view>
</template>
<script>
import waterFall from '@/components/waterFall/index'
import footerBar from '@/components/footerBar'
import share from '@/components/draw/share'
import msgPage from '@/components/msgPage'

import { toGoods } from '@/utils/navigateTo'
import './detail.scss'
export default {
  name: 'ProductMaterialDetail',
  components: {
    waterFall,
    footerBar,
    share,
    msgPage
  },
  data() {
    return {
      pageloaded: false,
      id: '',
      cover: '', // 封面图
      title: '', // 标题
      show_type: '',

      goodsDescImgs: [], // 商品介绍
      posterImgs: [], // 海报
      videos: [], // 视频
      productTests: [], // 产品实验
      reports: [], // 质检报告

      downloadPackage: {
        GOODS_INFO: [],
        POSTER_VIDEO: [],
        PRODUCT_TEST: [],
        REPORT: []
      },

      goods: {}, // 商品素材之商品信息

      tabList: [
        { type: 'GOODS_INFO', title: '商品介绍' },
        { type: 'POSTER_VIDEO', title: '海报/视频' },
        { type: 'PRODUCT_TEST', title: '产品实验' },
        { type: 'REPORT', title: '质检报告' }
      ],
      currentTab: 'GOODS_INFO',

      waterFallMinHeight: 0,

      // 分享模块
      shareBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/share/`,
      shareOption: { // 分享自定义设置
        share_content: '已有万人参与分享',
        share_url: '',
        share_list: []
      }
    }
  },
  computed: {},
  onLoad(options) {
    this.id = options.id || ''
    this.title = options.title || '详情'
    this.show_type = Number(options.show_type || '1')
    this.$setNavTitle(this.title)
    if (this.id) {
      this.fetchData()
    }
  },
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    // 获取详情
    async fetchData() {
      const res = await this.$api.materialApi.getMaterialDetail({ id: this.id })
      if (res.success && res.data) {
        const { cover, resource, goods } = res.data
        this.cover = Object.freeze(cover)
        this.goods = goods.length ? goods[0] : {}
        if (resource) {
          const { goodsDescImgs, posterImgs, videos, productTests, reports } = resource
          this.downloadPackage = Object.freeze({
            GOODS_INFO: goodsDescImgs || [],
            POSTER_VIDEO: posterImgs || [],
            PRODUCT_TEST: productTests || [],
            REPORT: reports || []
          })
          let imgWidth = (this.show_type === 1) ? 750 : (750 - 60) / 2
          this.goodsDescImgs = (goodsDescImgs || []).map((i, index) => {
            let needD = 0
            if (index === 1) {
              if ((goodsDescImgs[0].width / goodsDescImgs[0].height) === goodsDescImgs[1].width / goodsDescImgs[1].height) {
                needD = 60
              }
            }
            return {
              ...i,
              imgContainerHeight: Math.floor(imgWidth * i.height / i.width) - needD,
              imgHeight: Math.floor(imgWidth * i.height / i.width)
            }
          })
          if (this.show_type === 1) {
            imgWidth = (750 - 60) / 2
            this.posterImgs = (posterImgs || []).map((i, index) => {
              let needD = 0
              if (index === 1) {
                if ((posterImgs[0].width / posterImgs[0].height) === posterImgs[1].width / posterImgs[1].height) {
                  needD = 60
                }
              }
              return {
                ...i,
                imgContainerHeight: Math.floor(imgWidth * i.height / i.width) - needD,
                imgHeight: Math.floor(imgWidth * i.height / i.width)
              }
            })
            this.videos = videos || []
            this.productTests = (productTests || []).map((i, index) => {
              let needD = 0
              if (index === 1) {
                if ((productTests[0].width / productTests[0].height) === productTests[1].width / productTests[1].height) {
                  needD = 60
                }
              }
              return {
                ...i,
                imgContainerHeight: Math.floor(imgWidth * i.height / i.width) - needD,
                imgHeight: Math.floor(imgWidth * i.height / i.width)
              }
            })
            this.reports = (reports || []).map((i, index) => {
              let needD = 0
              if (index === 1) {
                if ((reports[0].width / reports[0].height) === reports[1].width / reports[1].height) {
                  needD = 60
                }
              }
              return {
                ...i,
                imgContainerHeight: Math.floor(imgWidth * i.height / i.width) - needD,
                imgHeight: Math.floor(imgWidth * i.height / i.width)
              }
            })
          }
        }

        this.initShare()
      }
      this.pageloaded = true
    },
    // 点击顶部分类
    tabClick(item) {
      this.currentTab = ''
      this.$nextTick(() => {
        this.currentTab = item.type
      })
    },
    // 视频播放，暂停其它视频
    videoPlay(e) {
      const index = Number(e.target.dataset.id)
      for (let i = 0; i < this.videos.length; i++) {
        if (i !== index) {
          console.log(i)
          this.$refs['video' + i][0].pause()
        }
      }
    },
    // 点击图片预览
    itemClick(item, list) {
      const urls = list.map(i => {
        if (i.resourceType === 1) {
          return i.resourceUrl
        }
      })
      uni.previewImage({
        current: item.resourceUrl,
        urls,
        indicator: 'number'
      })
    },
    // 点击商品,跳转商品详情
    toGoodsDetail() {
      if (this.goods && this.goods.goods_id) {
        toGoods(this.goods)
      }
    },
    // 数据统计
    async dataCount(data = {}) {
      // 数据统计："countType": "操作类型：1 ~ 分享统计，2 ~ 下载统计，3 ~ 浏览统计，4 ~ 复制统计,5 ~ 点赞统计",
      const res = await this.$api.materialApi.materialCount({ ...data })
      if (res.success) {
        // 成功
      }
    },
    async download(list, type = 'Image') {
      if (list && type === 'Video') {
        this.$downloadFile(list, {
          fileKey: 'resourceUrl',
          fileType: type,
          callback: (successNum, failNum) => {
            if (successNum > 0) {
              uni.showToast({ title: '已保存到本地相册', icon: 'none' })
            }
          }
        })
        return
      }

      const imgType = this.currentTab || 'GOODS_INFO'
      if (this.downloadPackage[imgType] && this.downloadPackage[imgType].length) {
        this.$navigateTo(`/pagesMaterial/product/download?id=${this.id}&show_type=${this.show_type}&type=${imgType}`)
      } else {
        uni.showToast({ title: '暂无数据', icon: 'none' })
      }
    },

    // 点击分享
    showSharePop() {
      if (this.token) {
        this.$refs.sharePop.show(this.shareOption)

        this.dataCount({ count_type: 1, id: this.id, user_id: this.userInfo.uid })
      } else {
        this.$navigateTo('/pages/login/index')
      }
    },

    // 分享初始化
    initShare() {
      if (this.token) {
        this.shareOption.share_title = this.title
        if (this.cover) {
          this.shareOption.share_image = this.cover
        }
        this.shareOption.share_url = ''
        this.shareOption.share_list = [
          {
            pic: this.cover,
            titleArr: [
              this.title
            ]
          }
        ]
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
